package com.example.springcloudgateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Component
public class PreFilter extends ZuulFilter {
    private Logger logger = LoggerFactory.getLogger(PreFilter.class);
    private static final String TRANCE_ID_KEY = "TRANCE_ID_KEY";

    public PreFilter() {
        super();
    }

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        logger.info("pre--模拟身份认证");
        // TODO: 2017/12/24  身份不通过，跟oauth,jwt
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.put("start", System.currentTimeMillis());
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        // 1.判断请求中是否存在。如果存在,立刻返回
        if (isExistTraceId(request)) {
            return null;
        }

        // 2.不存在就新生成一个
        String traceId = UUID.randomUUID().toString();
        logger.info("traceId：{}", traceId);
        RequestContext context = RequestContext.getCurrentContext();
        context.addZuulRequestHeader(TRANCE_ID_KEY, traceId);
        return null;
    }

    private boolean isExistTraceId(HttpServletRequest request) {
        String value = request.getHeader(TRANCE_ID_KEY);
        return !StringUtils.isBlank(value);
    }
}
